<template>
  <!--  头部-->
  <view class="head-wrapper">
    <view class="post-topic">
      <view class="topic-icon">#</view>&nbsp;
      <view :style="{paddingBottom: topicInfo == ''? '0px' : '8px'}">
        <u-tag v-show="topicInfo == ''" :text="topicInfo == ''  ? '选择话题' : topicInfo.name" size="mini"
               bgColor="transparent"
               borderColor="transparent"
               closeColor="#4ea4f9"
               color="#4ea4f9"
               :closable="topicInfo != ''" :show="closeTopicTag"
               plain
               @close="closeTopicTag = false"></u-tag>
      </view>
      <text v-show=" !closeTopicTag " class="topic-left-text">选择话题</text>&nbsp;
    </view>

    <view class="post-right" @click="showTopicPopup = !showTopicPopup">
      <text>选择话题或者模糊匹配话题列表</text>
      <image class="right-icon" src="https://www.douluodalu.icu:9000/school/static/right.png"></image>
    </view>


    <u-popup :safeAreaInsetBottom="false" overlay :show="showTopicPopup" @close="close" @open="open">
      <view>
        <index2 @topicInfo="getTopicInfo"/>
      </view>
    </u-popup>
  </view>
  <!--  内容-->
  <view class="post-content">
    <!--    文本内容-->
    <view padding="0" style="width: max-content;padding-bottom: 3rem">

          <textarea v-model="PostArticleDto.content"
                    placeholder="请输入内容"
                    :auto-focus="true"
                    maxlength="300"
                    :adjust-position="false"
                    :show-confirm-bar="false"
                    @focus="getFocusHeight"
                    auto-height></textarea>
    </view>
    <!--    图片视频内容-->
    <u-grid :border="false">
      <u-grid-item style="position: relative;" v-for="(item,index) in fileList1"
                   :key="index">
        <image v-if="isImageUrl(item)" @click="reviewImage(index)" class="content-images" :src="item"></image>
        <video style="position: relative" object-fit="fill" v-else class="content-images" :src="item">+
          <view @click="videoEdit(item,index)" class="video-text">编辑</view>
        </video>
        <image @click="deletePic(index)" class="close-images" src="https://www.douluodalu.icu:9000/school/static/close.png"></image>

      </u-grid-item>
      <u-grid-item v-show="fileList1.length > 0 && fileList1.length < 9">
        <view v-show="fileList1.length > 0 && fileList1.length < 9" @click="getMedia(1)" class="add-img-container">
          <image class="add-img" src="https://www.douluodalu.icu:9000/school/static/add_img.png"></image>
        </view>
      </u-grid-item>
    </u-grid>

    <!--    底部-->
    <view :style="{ bottom: keyboardHeight  +'px' }" id="bottom-list">
      <view>
        <image @click="getMedia(item.type)" style="padding: 0.6rem;width: 1.7rem;height: 1.7rem;" :src="item.url"
               :key="item.type" v-for="(item,index) in bottomList">
        </image>
      </view>
      <view>
        <u-button  @click="postTopic" :disabled="this.PostArticleDto.content == '' " shape="circle" type="primary" size="small">发布</u-button>
      </view>
    </view>
    <!--    //录音-->
    <view>
      <u-popup @close="recordClose"
               :overlay="false"
               mode="bottom" :show="recordShow">
        <view class="record-wrapper" :style="{ height: keyboardHeight1 - 10  +'px' }">
          <view class="record-layer">
            <view class="record-box">
              <view class="record-btn-layer" v-if="tempFilePath == ''">
                <button class="record-btn" :class="longPress == '1' ? 'record-btn-1' : 'record-btn-2'"
                        @longpress="longpressBtn()" @touchend="touchendBtn()">
                  <image style="width: 3rem;height: 3rem;" src="https://www.douluodalu.icu:9000/school/static/record.png"/>
                </button>
                <text>{{ longPress == '1' ? '按住说话' : '说话中...' }}</text>
              </view>
              <view class="record-btn-layer" v-else>
                <button class="record-btn" @longpress="delShow = true" @click="playBtn()"
                        :class="playStatus == '1' ? 'record-btn-2' : 'record-btn-1'">
                  <image style="width: 3rem;height: 3rem;" src="https://www.douluodalu.icu:9000/school/static/on.png"/>
                </button>
                <text style="">
                  {{ playStatus == '1' ? (count + "''") : '点击播放' }}
                </text>
              </view>
              <!-- 语音音阶动画 -->
              <view class="prompt-layer prompt-layer-1" v-show="longPress == '2' ">
                <view style="padding-bottom: 5rem;display: flex;width: 100%;
                flex-direction: row;border-radius: 15px;justify-content: space-around;align-items: center;background-color: rgba(157,156,156,0.03)">
                  <view class="prompt-loader">
                    <view class="em" v-for="(item,index) in 15" :key="index"></view>
                  </view>
                  <text class="p">&nbsp;&nbsp;{{ (count - 60) * -1 }}"</text>
                  <view class="prompt-loader">
                    <view class="em" v-for="(item,index) in 15" :key="index"></view>
                  </view>
                </view>
              </view>
              <view class="prompt-layer prompt-layer-1" v-show="!longPress == '2' ">
                <view style="padding-bottom: 5rem;display: flex;width: 100%;
                flex-direction: row;border-radius: 15px;justify-content: space-around;align-items: center;background-color: rgba(157,156,156,0.03)">
                  <text class="p">&nbsp;&nbsp;{{ time }}"</text>
                </view>
              </view>
              <!-- 删除 -->
              <view class="delete" v-if="delShow" @click.stop="delBtn()">
                <u-button :hairline="false" round="50%" shape="circle" icon="trash"></u-button>
                <audio :src="tempFilePath"></audio>
              </view>
            </view>
          </view>
        </view>
      </u-popup>
    </view>

  </view>

</template>
<script>
import index2 from "@/components/topic/index2.vue";
import authorize from "@/utils/authorize";
import env from "@/utils/env";
import {getToken} from "@/utils/auth";
import {postArticle} from "@/api/article";
import {deletePic} from "@/api/comment";

const recorderManager = uni.getRecorderManager()
const innerAudioContext = uni.createInnerAudioContext()
var init // 录制时长计时器
var timer // 播放 录制倒计时
export default {
  components: {
    index2
  },
  data() {
    return {
      topicInfo: '',
      showTopicPopup: false,
      closeTopicTag: true,
      count: null, // 录制倒计时
      voiceShow: false,
      longPress: '1', // 1显示 按住说话 2显示 说话中
      delShow: false, // 删除提示框显示隐藏
      time: 0, //录音时长
      duration: 60000, //录音最大值ms 60000/1分钟
      tempFilePath: '', //音频路径
      playStatus: 0, //录音播放状态 0:未播放 1:正在播放
      recordShow: false,
      //键盘高度
      keyboardHeight: 0,
      keyboardHeight1: 0,
      // 聊天框距离底部的高度
      bottomHeight: 0,
      text: '',
      tempFilePaths: [],
      PostArticleDto: {
        channelId: "",
        channelName: "",
        channelImage: "",
        channelParentId: "",
        content: "",
        images: [],
        videos: [],
        voice: ""
      },
      fileList1: [],
      bottomList: [
        {
          url: 'https://www.douluodalu.icu:9000/school/static/post_image.png',
          type: 1
        },
        // {
        //   url: 'https://www.douluodalu.icu:9000/school/static/post_video.png',
        //   type: 2
        // },
        // {
        //   url: 'https://www.douluodalu.icu:9000/school/static/voice.png',
        //   type: 3
        // },
        // {
        //   url: 'https://www.douluodalu.icu:9000/school/static/post_emoj.png',
        //   type: 4
        // },
        // {
        //   url: 'http://49.233.248.28:9000/school/static/aite.png',
        //   type: 5
        // },
      ]
    }
  },
  onLoad() {
    uni.onKeyboardHeightChange(res => {
      this.keyboardHeight = res.height
      if (this.keyboardHeight < 0) this.keyboardHeight = 0;
      if (this.keyboardHeight > 0) this.keyboardHeight1 = this.keyboardHeight;
    })
  },
  onUnload() {
    uni.offKeyboardHeightChange()//如果不传入监听的对象，则移除所有监听函数
    // if(this.PostArticleDto.content.length != 0){
      // uni.showModal({
      //   title: '是否保留本次编辑?',
      //   content: '保留后，再次进入可继续编辑',
      //   cancelText: '不保留',
      //   confirmText: '保留',
      //   confirmColor: '#4ea4f9',
      //   success(res) {
      //     if (res.confirm) {
      //       uni.reLaunch({
      //         url: '/pages/index/index'
      //       });
      //     } else if (res.cancel) {
      //       uni.switchTab({
      //         url: '/pages/index/index'
      //       });
      //     }
      //   }
      // })
    // }else {
    //   uni.reLaunch({
    //     url: '/pages/index/index'
    //   });
    // }
  },
  methods: {
    async performAsyncOperation() {
      // 执行异步操作，例如网络请求
      return new Promise((resolve) => {
        // 模拟异步操作，可以替换成实际的异步逻辑
        setTimeout(() => {
          resolve();
        }, 1000);
      });
    },

    async postTopic() {
      uni.showLoading({
        title: '发布中',
        mask: true
      })
      if(this.PostArticleDto.channelId == ''){
        this.showTopicPopup = true
        uni.showToast({
          title: '请选择话题',
          icon: 'none',
          position: 'bottom'
        })
        return
      }
      if(this.fileList1.length > 0){
        this.fileList1.forEach(item => {
          if(this.isImageUrl(item)){
            this.PostArticleDto.images.push(item)
          }else {
            this.PostArticleDto.videos.push(item)
          }
        })
      }

      const res = await  postArticle(this.PostArticleDto)
      this.text = ''
      this.tempFilePaths = []
      this.fileList1 = []
      this.PostArticleDto = {}
      this.tempFilePath =  ''
      this.topicInfo = ''
      if(res.code == '200' && res.data?.id !== undefined){
        uni.hideLoading()
        uni.$emit('newPost', { data:res.data });
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/index/index'
          });
        }, 500);

      }else {
        uni.hideLoading()
        uni.showToast({
          title: res.data,
          icon: 'none'
        })
      }

    },
    reviewImage(index) {
      uni.previewImage({
        current: index,
        urls: this.fileList1,
        longPressActions: {
          itemList: ['发送给朋友', '保存图片', '收藏'],
          success: function (data) {
          },
          fail: function (err) {
          }
        }
      });
    },
    videoEdit(url, index) {
      uni.openVideoEditor({
        filePath: url,
        success: res => {
          // 第一个参数是索引，第二个参数是要删除的元素的个数，第三个参数是替换的元素
          this.fileList1.splice(index, 1, res.tempFilePath);
          this.PostArticleDto.images = this.fileList1
        }
      });
    },
    isImageUrl(url) {
      const dotIndex = url.lastIndexOf(".");
      // 截取路径的扩展名
      const extension = url.substring(dotIndex);
      // 判断扩展名是否是图片扩展名
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tif', '.tiff'];
      return imageExtensions.includes(extension);
    },
    getTopicInfo(topicInfo) {
      this.topicInfo = topicInfo
      this.PostArticleDto.channelId = this.topicInfo.id
      this.PostArticleDto.channelName = this.topicInfo.name
      this.PostArticleDto.channelImage = this.topicInfo.url
      this.PostArticleDto.channelParentId = this.topicInfo.parent
      this.showTopicPopup = false
      this.closeTopicTag = true
      // this.topicInfo.name = '选择话题'
    },
    open() {
    },
    close() {
      this.showTopicPopup = false
    },
    // 倒计时
    countdown(val) {
      let _then = this;
      _then.count = Number(val);
      timer = setInterval(function () {
        if (_then.count > 0) {
          _then.count--
        } else {
          _then.longPress = '1';
          clearInterval(timer);
        }
      }, 1000);
    },
    // 长按录音事件
    longpressBtn() {
      this.longPress = '2';
      this.countdown(60); // 倒计时
      clearInterval(init) // 清除定时器
      recorderManager.onStop((res) => {
        this.tempFilePath = res.tempFilePath;
        this.recordingTimer(this.time);
      })
      const options = {
        duration: this.duration, // 指定录音的时长，单位 ms
        sampleRate: 16000, // 采样率
        numberOfChannels: 1, // 录音通道数
        encodeBitRate: 96000, // 编码码率
        format: 'mp3', // 音频格式，有效值 aac/mp3
        frameSize: 10, // 指定帧大小，单位 KB
      }
      this.recordingTimer();
      recorderManager.start(options);
      // 监听音频开始事件
      recorderManager.onStart((res) => {
      })
    },
    // 长按松开录音事件
    touchendBtn() {
      this.longPress = '1';
      recorderManager.onStop((res) => {
        this.tempFilePath = res.tempFilePath
        this.PostArticleDto.voice = this.tempFilePath
      })
      this.recordingTimer(this.time)
      recorderManager.stop()
      this.delShow = true;

    },
    recordingTimer(time) {
      var that = this;
      if (time == undefined) {
        // 将计时器赋值给init
        init = setInterval(function () {
          that.time++
        }, 1000);
      } else {
        clearInterval(init)
      }
    },
    // 删除录音
    delBtn() {
      // this.delShow = false;
      this.time = 0
      this.tempFilePath = ''
      this.PostArticleDto.voice = ''
      this.playStatus = 0
      innerAudioContext.stop()
    },
    // 播放
    playBtn() {
      innerAudioContext.src = this.tempFilePath
      //在ios下静音时播放没有声音，默认为true，改为false就好了。
      // innerAudioContext.obeyMuteSwitch = false
      //点击播放
      if (this.playStatus == 0) {
        this.playStatus = 1;
        innerAudioContext.play();
        this.countdown(this.time); // 倒计时
      } else {
        this.playStatus = 0;
        innerAudioContext.pause()
      }
      // //播放结束
      innerAudioContext.onEnded(() => {
        this.playStatus = 0;
        innerAudioContext.stop();
      })
    },
    getFocusHeight() {
      uni.getSelectedTextRange({
        success: res => {
        }
      })
    },
    recordClose() {
      this.recordShow = false
    },
    // 删除图片
    deletePic(index) {
      this.fileList1.splice(index, 1)
      deletePic( this.fileList1[index])
      this.PostArticleDto.images = this.fileList1
    },
    // 新增图片
    uploadFile(tempFilePaths) {
      // for (let i = 0; i < tempFilePaths.length; i++) {
      uni.uploadFile({
        url: this.$BASE_UPLOAD, //仅为示例，非真实的接口地址
        filePath: tempFilePaths,
        // filePath: tempFilePaths[i],
        name: 'file',
        header: {
          'Authorization': getToken(),
        },
        // formData: {
        //   'user': 'test'
        // },
        success: (uploadFileRes) => {
          let res = (JSON.parse(uploadFileRes.data)).data.url
          this.fileList1.push(res)
        }
      })
      // }
    },
    getMedia(type) {
      let _this = this
      if (type === 1 || type === 2) {
        if (this.fileList1.length >= 9) {
          uni.showToast({
            title: '最多上传9张图片哦',
            icon: 'none',
            duration: 2000
          })
          return
        }
        this.recordShow = false
        this.$authorize('camera', false, true).then(() => {
          //成功授权后相应逻辑
          if (type === 1) {
            uni.chooseMedia({
              count: 9 - this.fileList1.length,
              mediaType: ['image'],
              //可以指定是原图还是压缩图，默认二者都有
              sourceType: ['camera', 'album'], //从相册选择
              success: res => {
                console.log(res)
                res.tempFiles.forEach(item => {
                  _this.uploadFile(item.tempFilePath)
                })
                if (_this.fileList1.length > 9) {
                  _this.fileList1.splice(9, _this.fileList1.length - 9);
                  uni.showToast({
                    title: '最多选择九个哦',
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            });
          }
          if (type === 2) {
            uni.chooseMedia({
              count: 9 - this.fileList1.length,
              mediaType: ['video'],
              sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
              sourceType: ['camera', 'album'], //从相册选择
              success: function (res) {
                res.tempFiles.forEach(item => {
                  _this.uploadFile(item.tempFilePath)
                })
                if (_this.fileList1.length > 9) {
                  _this.fileList1.splice(9, _this.fileList1.length - 9);
                  uni.showToast({
                    title: '最多选择九个哦',
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            });
          }
        }).catch(() => {
          uni.showToast({title: '请先授权相机权限'})
        }).finally(() => {
          //无论授权成功或者失败都执行的逻辑
        });
      }
      if (type === 3) {
        this.keyboardHeight = this.keyboardHeight1;
        authorize('record', false, true).then(() => {
          this.keyboardHeight = this.keyboardHeight1;
          //成功授权后相应逻辑
          this.recordShow = true;
        }).catch(() => {
          //拒绝授权后相应逻辑
          uni.showToast({title: '请先授权麦克风权限'})
        }).finally(() => {
          //无论授权成功或者失败都执行的逻辑
        });
      }
      if (type === 4) {
        this.recordClose()
        this.keyboardHeight = this.keyboardHeight1;
        uni.showToast({title: '表情功能正在开发中'})
      }
      if (type === 5) {
        this.recordClose()
        this.keyboardHeight = this.keyboardHeight1;
        uni.showToast({title: '@功能正在开发中'})

      }
    },
  }
}
</script>

<style lang="scss">

.head-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: rgba(0, 0, 0, 0.02);
  padding: 0 1rem;
  height: 2.5rem;
  position: relative;
}

.right-icon {
  height: 1rem;
  width: 1rem;
  padding-left: 0.5rem;
}

.topic-icon {
  height: 0.6rem;
  padding: 0.2rem;
  border-radius: 50%;
  color: white;
  font-weight: bold;
  background-color: #4ea4f9;
  display: flex;
  align-items: center;
  justify-content: center;
}

.topic-left-text {
  padding-left: 0.2rem;
  color: #4ea4f9;
  font-size: 12px;
}

.post-topic {
  display: flex;
  align-items: center;
  color: #4ea4f9;
}

.post-right {
  display: flex;
  align-items: center;
  color: rgba(192, 192, 192, 0.67);
  font-size: 0.7rem;
}

.post-content {
  padding: 0 0.79rem;
}

#bottom-list {
  width: 90vw;
  position: absolute;
  height: 2rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.record-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1px solid rgba(229, 229, 229, 0.47);
}

.record-btn {
  width: 5rem;
  height: 5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: #4ea4f9;
}

/* 语音录制开始--------------------------------------------------------------------- */
.record-layer {
  padding: 300px 0;
  box-sizing: border-box;
}

.record-box {
  width: 100%;
  position: relative;
}

.record-btn-layer {
  display: flex;
  justify-content: center;
  flex-direction: column;
  text-align: center;
  line-height: 3rem;
  position: relative;
}

.delete {
  position: absolute;
  left: -6rem;
  top: 1.5rem;
}

.record-btn-layer text {
  padding: 10px 0;
}

.record-btn-layer button::after {
  border: none;
}

.record-btn-layer button {
  font-size: 14px;
  height: 5rem;
  width: 5rem;
  border-radius: 50%;
  text-align: center;
  background: #4ea4f9;
}

.record-btn-layer button image {
  width: 16px;
  height: 16px;
  margin-right: 4px;
  vertical-align: middle;
}

.record-btn-layer .record-btn-2 {
  //background: rgba(78, 164, 249, 0.55) url("/record.png");
}

/* 提示小弹窗 */
.prompt-layer {
  line-height: 1.5rem;
  box-sizing: border-box;
  position: absolute;
  padding: 3rem;
  left: 50%;
  transform: translateX(-50%);
}

.prompt-layer::after {
  content: '';
  display: block;
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
}

.prompt-layer-1 {
  font-size: 12px;
  width: 128px;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  top: -130px;
}

.prompt-layer-1 .p {
  color: #000000;
  font-weight: bold;
  font-size: 2rem;
  margin-left: -0.5rem;
}

.prompt-layer-1 .span {
  color: rgba(0, 0, 0, .6);
}

.prompt-loader .em {
  width: 2px;
  color: rgba(192, 192, 192, 0.44);
  background-color: rgba(192, 192, 192, 0.44);
}

/* 语音音阶------------- */
.prompt-loader {
  padding: 3rem;
  display: flex;
  width: 96px;
  height: 20px;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}

.prompt-loader .em {
  background-color: rgba(192, 192, 192, 0.5); //声波颜色
  width: 3px;
  height: 6px;
  margin: 0 0.03rem;
  display: inline-block;
  border: none;
}

.prompt-loader .em:last-child {
  margin-right: 0px;
}

.prompt-loader .em:nth-child(1) {
  animation: load 2.5s 1.4s infinite linear;
}

.prompt-loader .em:nth-child(2) {
  animation: load 2.5s 1.2s infinite linear;
}

.prompt-loader .em:nth-child(3) {
  animation: load 2.5s 1s infinite linear;
}

.prompt-loader .em:nth-child(4) {
  animation: load 2.5s 0.8s infinite linear;
}

.prompt-loader .em:nth-child(5) {
  animation: load 2.5s 0.6s infinite linear;
}

.prompt-loader .em:nth-child(6) {
  animation: load 2.5s 0.4s infinite linear;
}

.prompt-loader .em:nth-child(7) {
  animation: load 2.5s 0.2s infinite linear;
}

.prompt-loader .em:nth-child(8) {
  animation: load 2.5s 0s infinite linear;
}

.prompt-loader .em:nth-child(9) {
  animation: load 2.5s 0.2s infinite linear;
}

.prompt-loader .em:nth-child(10) {
  animation: load 2.5s 0.4s infinite linear;
}

.prompt-loader .em:nth-child(11) {
  animation: load 2.5s 0.6s infinite linear;
}

.prompt-loader .em:nth-child(12) {
  animation: load 2.5s 0.8s infinite linear;
}

.prompt-loader .em:nth-child(13) {
  animation: load 2.5s 1s infinite linear;
}

.prompt-loader .em:nth-child(14) {
  animation: load 2.5s 1.2s infinite linear;
}

.prompt-loader .em:nth-child(15) {
  animation: load 2.5s 1.4s infinite linear;
}

@keyframes load {
  0% {
    height: 10%;
  }
  50% {
    height: 100%;
  }
  100% {
    height: 10%;
  }
}

/* 语音音阶-------------------- */
.prompt-layer-2 {
  top: -40px;
}

.prompt-layer-2 .text {
  color: rgba(0, 0, 0, 1);
  font-size: 12px;
}

/* 语音录制结束---------------------------------------------------------------- */

.content-images {
  border-radius: 5px;
  width: 7.5rem;
  height: 7.5rem;
}

.add-img-container {
  //position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: -1.35rem;
  background-color: rgba(192, 192, 192, 0.11);
  border-radius: 3px;
  width: 7.5rem;
  height: 7.5rem;
}

.add-img-container image {
  scale: 0.6;
}

.add-img {
  border-radius: 5px;
  width: 7.5rem;
  height: 7.5rem;
}

.close-images {
  //display: flex;
  z-index: 99;
  position: relative;
  color: #fff;
  left: 3.5rem;
  top: -7.6rem;
  margin-left: -15px;
  outline: none;
  //right: -4.5rem;
  width: 1.5rem;
  height: 1.5rem;

}

.video-text {
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  bottom: 0.3rem;
  left: 0.2rem;
  color: #fff;
  height: 1rem;
  padding: 2px;
  width: 2rem;
  z-index: 99;
  border-radius: 72rpx;
  font-size: 12px;
  background-color: rgba(0, 0, 0, 0.82);

}


</style>
